package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.DemoModeException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class DemoModeInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是演示模式，直接放行
        String demoMode = sysConfigService.selectConfigByKey("sys.demoMode");
        if (StringUtils.isEmpty(demoMode) || !Convert.toBool(demoMode)) {
            return true;
        }

        String url = request.getRequestURI();

        // 需要放行的URL
        if (StringUtils.isNotEmpty(url) && (url.contains("/demo") || url.contains("/tool/gen"))) {
            return true;
        }

        // 需要拦截的URL
        if (StringUtils.isNotEmpty(url) && (url.indexOf("/genCode") >= 0 || url.indexOf("/export") >= 0)) {
            throw new DemoModeException();
        }

        // 拦截增删改操作
        String method = request.getMethod();
        if ("DELETE".equals(method) || "POST".equals(method) || "PUT".equals(method)) {
            throw new DemoModeException();
        }

        return true;
    }
}